package distriKub;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;

import javax.swing.JOptionPane;

public class DBComClient {

	static Socket clientSocket = null;
	static BufferedReader is = null;
	static PrintStream os = null;
	String responseLine;
	
	InetAddress ServerAddress;
	
	public DBComClient(InetAddress ServerAddress){
		this.ServerAddress = ServerAddress;
	}
	
	public String sendDBQuery(String theQuery, InetAddress theAddress, int thePort, int timeToWait) {
		String DBresult = null;
		
		try {
			clientSocket = new Socket(theAddress, thePort);
			clientSocket.setSoTimeout(timeToWait);
			is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
			os = new PrintStream(clientSocket.getOutputStream());
		} catch (IOException IOEX) {
			System.out.println("\n===> DBComClient.java ===> Error Creating new Socket\n");
			IOEX.printStackTrace();
			DBresult = ComRules.DBComError;
		} // End of catch block
		
		if (clientSocket != null && os != null && is != null) {
			os.println(theQuery);
		}
		
		try{ 
		    if ((responseLine = is.readLine()) == null){
		    	System.out.println("==> DBComClient.java ==> WARNING : responseLine is null (Exiting...)");
		    	DBresult = ComRules.DBComError;
		    }
		    
		    if ((responseLine.equals(ComRules.DBOKRegistered))){
		    	DBresult = ComRules.DBOKRegistered;
		    }
		} catch (IOException e) {
		    System.err.println("IOException:  " + e);
		    DBresult = ComRules.DBComError;
		}
		
		return DBresult;
	} // End of sendDBQuery method
	
	public void registerInServerDB(int playerId, String playerUserName, String playerPassword){
		String DBresult = sendDBQuery(ComRules.RegisterNewPlayer + ComRules.MessageDelimiter + playerId + "," + playerUserName + "," + playerPassword, ServerAddress, ComRules.serverPort, ComRules.DBResponseTimeout);
		if (DBresult.equals(ComRules.DBOKRegistered))
			JOptionPane.showMessageDialog(null, "Registration completed successfully");
		if (DBresult.equals(ComRules.DBERRORRegistered))
			JOptionPane.showMessageDialog(null, "Username or Id already exists in the database.\nPlease try again with different input.","Username/Id already taken", JOptionPane.ERROR_MESSAGE);
		if (DBresult.equals(ComRules.DBComError))
			JOptionPane.showMessageDialog(null, "The communication to the server seems to be down.\n Please try again later...","No communication to the server", JOptionPane.ERROR_MESSAGE);
	}
	
}
